<?php


namespace App\Models\OpenShop\SiteLocation;


use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\BaseModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\Wanggui\WangguiSiteDistrictModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class OpenShopSiteLocationExamineLogModel extends BaseModel
{
    use KfUid;

    use KfSoftDeletes;

    protected $table = 'open_shop_site_location_examine_logs';

    protected $fillable = [
        'id',
        'source',
        'orderNo',
        'content',
        'status',
        'createdAt',
        'createdByUid',
        'updatedByUid',
        'updatedAt',
        'isToStore',
        'isDeleted',
        'position',
        'type',
        'extra',
        'flowOfPeopleScores',
        'customerGroupType',
        'passengerFlowDrive',
        'openPotential',
    ];

    protected $appends = [
        'customerGroupTypeFormat',
        'passengerFlowDriveFormat'
    ];

//    const EXAMINE_COUNT_1 = 1; //选址负责人待审批
//    const EXAMINE_COUNT_2 = 2; //审批完成

    //之前是上面的
    const EXAMINE_COUNT_0 = 0; //
    const EXAMINE_COUNT_1 = 1; //选址负责人
    const EXAMINE_COUNT_2 = 2; //省总
    const EXAMINE_COUNT_3 = 3; //战区总
    const EXAMINE_COUNT_4 = 4; //招商核实
    const EXAMINE_COUNT_5 = 5; //审批完成

    const POSITION_OTHER_EXAMINE    = 3;
    const POSITION_GENERAL_EXAMINE  = 2;
    const POSITION_PROVINCE_EXAMINE = 0;
    const POSITION_CHARGE_EXAMINE   = 1;
    const POSITION_BUSINESS_EXAMINE = 4;
    const POSITION_VERIFY_PERSONNEL = 5;
    const POSITION_WAR_ZONE_MANAGER = 6;

    const POSITION_EXAMINE_MAPPING = [
        self::POSITION_OTHER_EXAMINE    => '其他',
        self::POSITION_PROVINCE_EXAMINE => '省区负责人',
        self::POSITION_CHARGE_EXAMINE   => '选址负责人',
        self::POSITION_GENERAL_EXAMINE  => '总部负责人',
        self::POSITION_BUSINESS_EXAMINE => "商家",
        self::POSITION_VERIFY_PERSONNEL => "核查专员",
        self::POSITION_WAR_ZONE_MANAGER => "战区负责人",
    ];

    const POSITION_SITE_MAP = [
        self::POSITION_CHARGE_EXAMINE  => ConfigModel::SITE_MANAGER,
        self::POSITION_GENERAL_EXAMINE => ConfigModel::SITE_SUPER_ADMIN,
    ];

    /**
     * 审批流 - 配置
     */
    const APPROVE_PROCEDURE = [
        //招商自带址审批流
        "solicitBusinessManagerApprove" => [
            OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE,
            OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE,
            OpenShopSiteLocationExamineLogModel::POSITION_GENERAL_EXAMINE
        ]
    ];

    /**
     * 获取审批人
     *
     * @param int $approveProcedureType
     * @param OpenShopSiteLocationModel|null $siteLocationModel
     * @return array|mixed
     * @throws \Exception
     */
    public static function getApproveProcedureUser(int $approveProcedureType, OpenShopSiteLocationModel $siteLocationModel = null)
    {
        switch ($approveProcedureType){
            case OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE:
                return [(new OpenShopOrganizationManageModel())->getOrganizationManageId($siteLocationModel->provinceCode, $siteLocationModel->cityCode, 1)];
                break;
            case  OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE:
            case OpenShopSiteLocationExamineLogModel::POSITION_GENERAL_EXAMINE:
                return ConfigModel::getManager(OpenShopSiteLocationExamineLogModel::POSITION_SITE_MAP[$approveProcedureType]);
                break;
            default:
                throw new \Exception("尚未注册该审批类型审批人获取方法");
                break;
        }
    }

    /**
     * 获取已审批的数量
     *
     * @param string $orderNo
     * @return int
     */
    public static function getExistsApproveCount(string $orderNo): int
    {
        return self::query()
                   ->where('orderNo', $orderNo)
                   ->where('status',
                       OpenShopSiteLocationExamineLogModel::STATUS_OK)
                   ->count();
    }

    const STATUS_OK     = 1; // 通过    提交
    const STATUS_REFUSE = 2; // 拒绝

    const STATUS_MAPPING = [
        self::STATUS_OK     => '同意',
        self::STATUS_REFUSE => '驳回',
    ];

    const IS_TO_STORE_YES = 1;
    const IS_TO_STORE_NO  = 0;

    const IS_TO_STORE_MAPPING = [
        self::IS_TO_STORE_NO  => '否',
        self::IS_TO_STORE_YES => '是',
    ];


    //复用一下IS_TO_STORE
    const IS_NEW_YES = 1;
    const IS_NEW_NO  = 0;

    const IS_NEW_MAPPING = [
        self::IS_NEW_NO  => '否',
        self::IS_NEW_YES => '是',
    ];


    const SOURCE_PLACEHOLDER      = 2;
    const SOURCE_HOUSE            = 1;
    const SOURCE_OPEN_SHOP        = 0;
    const SOURCE_LEASE_CONTRACT   = 10;
    const SOURCE_TRANSFER_HOUSE   = 11;
    const SOURCE_WG_AUDIT         = 20;
    const SOURCE_OTHER_WG_AUDIT   = 21;  //其他网规评估
    const SOURCE_SITE_FROM_SUBMIT = 22;  //选址表单提交

    const SOURCE_MAPPING = [
        self::SOURCE_PLACEHOLDER      => '预占址审批',
        self::SOURCE_HOUSE            => '房源审批',
        self::SOURCE_OPEN_SHOP        => '选址审批',
        self::SOURCE_LEASE_CONTRACT   => '租赁合同审批',
        self::SOURCE_TRANSFER_HOUSE   => '房源转让',
        self::SOURCE_WG_AUDIT         => '网规评估',
        self::SOURCE_OTHER_WG_AUDIT   => '其他网规评估',
        self::SOURCE_SITE_FROM_SUBMIT => '表单提交',
    ];


    const TYPE_DEFAULT                        = 0;
    const TYPE_BUSINESS_CONFIRM_SITE_LOCATION = 1;


    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format("Y-m-d H:i:s");
    }

    public function siteLocationRel(): HasOne
    {
        return $this->hasOne(OpenShopSiteLocationModel::class, 'orderNo', 'orderNo')->whereIn('source',
            [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP, OpenShopSiteLocationModel::SOURCE_HOUSING]);
    }

    public function signOrderRel(): HasOne
    {
        return $this->hasOne(OpenShopSignOrderModel::class, 'orderNo', 'orderNo');
    }

    public function getPlaceHolderStatus()
    {

    }


    //获得已经审批通过的
    public static function getExaminersOk(string $orderNo): array
    {
        return self::query()->where('orderNo', $orderNo)->where("source", OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                   ->where('status', self::STATUS_OK)->pluck('createdByUid')->toArray();
    }

    //获得已经审批通过的数量
    public static function getStatusOkCount(string $orderNo): int
    {
        return self::query()->where('orderNo', $orderNo)->where("source", OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                   ->where('status', self::STATUS_OK)->count();
    }

    public function resourceRelByWanggui()
    {
        return $this->hasMany(ResourcesModel::class, 'businessId', 'id')->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)->where('business', ResourcesModel::BUSINESS_WG_AUDIT)->where('businessId', '>', 0);
    }


    /**
     * 获取网规沙盘评估下的所有文件
     * @return HasMany
     */
    public function resourceRelByCover(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId', 'id')->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)->where('business', ResourcesModel::BUSINESS_WG_AUDIT)->where('name', ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION);
    }

    public function resourceRelUsedToShow()
    {
        return $this->hasMany(ResourcesModel::class, 'businessId', 'id')
            ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
            ->where(function($query){
                $query->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                    ->orWhere('business', ResourcesModel::BUSINESS_OPEN_DISTRICT);
            })
            ->where('businessId', '>', 0);
    }

    public function wangguiSiteDistrictRel()
    {
        return $this->hasMany(WangguiSiteDistrictModel::class, 'relationId', 'id');
    }

    public function getCustomerGroupTypeFormatAttribute()
    {
        $keys    = explode(',', $this->customerGroupType);
        $typeArr = [];
        foreach ($keys as $key) {
            $typeArr[] = ProgrammingEnum::CUSTOMER_GROUP_MAPPING[$key] ?? '';
        }
        return implode(',', $typeArr);
    }

    public function getPassengerFlowDriveFormatAttribute()
    {
        $keys    = explode(',', $this->passengerFlowDrive);
        $typeArr = [];
        foreach ($keys as $key) {
            $typeArr[] = SiteLocationEnum::DRIVE_TYPE_TEXT[$key] ?? '';
        }
        return implode(',', $typeArr);
    }
}
